package zcatt.ex008.ui.navigator;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionDelegate;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

public class DeleteChapterAction extends ActionDelegate {

	private IStructuredSelection selection = StructuredSelection.EMPTY;

	@Override
	public void selectionChanged(IAction action, ISelection sel) {
		if(sel instanceof IStructuredSelection)
			selection = (IStructuredSelection) sel;
		else
			selection = StructuredSelection.EMPTY;
	}

	
	@Override
	public void run(IAction action) {
		WorkspaceModifyOperation deleteChapterOperation = new WorkspaceModifyOperation() {
			@Override
			protected void execute(IProgressMonitor monitor) throws CoreException {
				// In production code, you should always externalize strings, but this is an example.
				monitor.beginTask("Deleting property from selection", 5); 
				try {
					if(selection.size() == 1) {

						Object firstElement = selection.getFirstElement();
						if(firstElement instanceof ChapterTreeData) {
							ChapterTreeData data = (ChapterTreeData) firstElement;

							IFile file = data.getFile();
							monitor.worked(1);

							if(file != null && file.isAccessible()) {
								Pattern pattern = Pattern.compile("^Chapter\\s\\w+", Pattern.CASE_INSENSITIVE);

								try {
									// persist the model to a temporary storage medium (byte[])
									ByteArrayOutputStream output = new ByteArrayOutputStream();
									PrintWriter printWriter = new PrintWriter(output, true);
									
									// load the model
									BufferedReader reader = new BufferedReader(new InputStreamReader(file.getContents()));
									String line;
									while((line = reader.readLine())!= null)
									{
										Matcher m = pattern.matcher(line);
										if(m.find())
										{
											ChapterTreeData cur = new ChapterTreeData(m.group(0), file);
											if(data.equals(cur))
											{
												System.out.println("skip print "+cur);
												continue;
											}
										}		

										printWriter.println(line);
									}
									monitor.worked(3);
									
									// set the contents of the properties file
									file.setContents(
														new ByteArrayInputStream(output.toByteArray()),
																IResource.FORCE | IResource.KEEP_HISTORY, monitor);
									monitor.worked(2);
									
								} catch (IOException e) {
									// handle error gracefully
									Platform.getLog(DeleteChapterAction.class).error("Could not delete chapter!", e);
									MessageDialog.openError(Display.getDefault().getActiveShell(),
											"Error Deleting Chapter", 
											"Could not delete chapter!");   
								}

							} else // shouldn't happen, but handle error condition
								MessageDialog.openError(Display.getDefault().getActiveShell(),
														"Error Deleting Chapter",  
														"The text file was not accessible!");   

						} else // shouldn't happen, but handle error condition
							MessageDialog.openError(Display.getDefault().getActiveShell(),
										"Error Deleting Chapter",  
										"The element that was selected was not of the right type.");   
					} else // shouldn't happen, but handle error condition
						MessageDialog.openError(Display.getDefault().getActiveShell(),
									"Error Deleting Chapter",  
									"An invalid number of chapters were selected.");   
				} finally {
					monitor.done();
				}
			}
		};
		try {
			PlatformUI.getWorkbench().getProgressService().run(true, false, deleteChapterOperation);
		} catch (InvocationTargetException | InterruptedException e) {
			// handle error gracefully
			Platform.getLog(DeleteChapterAction.class).error("Could not delete chapter!", e); 
			MessageDialog.openError(Display.getDefault().getActiveShell(),
					"Error Deleting Chapter",  
					"Could not delete chapter!");  
		}
	}


}
